package com.example.springsecurity.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder pw;

    //这里就是做我们自定义的登录逻辑 username就是前端传过来的
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1. 查询数据库判断用户名是否存在, 入宫不存在就会抛出UsernameNotFound异常
        if(!"admin".equals(username)){
            throw new UsernameNotFoundException("用户名不存在!");
        }
        //2. 把查询出来的密码(注册时已经加密)进行解析, 或者直接把密码放入构造方法
        String password = pw.encode("123");
        //注意这个user是security中定义的
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_base,/main.html,/insert"));
    }
}